package org.mte.sakn.file;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StringReader;

public class FileObjectImpl extends File implements FileObject, Serializable {


	private static final long serialVersionUID = -8362647567194803975L;


	/**
	 * File's content
	 */
	protected ByteArrayOutputStream content = null;
	
	/**
	 * FileObjectImpl
	 * @param file
	 */
	public FileObjectImpl(File file) {
		super(file.getAbsolutePath());
	}

	/**
	 * FileObjectImpl
	 * @param pathName
	 */
	public FileObjectImpl(String pathName) {
		super(pathName);
	}

	
	/**
	 * loadContent
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void loadContent() throws FileNotFoundException, IOException {
		InputStream	inputStream = new FileInputStream(getPath());
		content = new ByteArrayOutputStream();
		int outByte;
		while ((outByte = inputStream.read()) != -1) {
			content.write(outByte);
		}
		inputStream.close();
		inputStream = null;
		content.close();
	}
	
	/**
	 * getContent
	 * @return content
	 */
	public ByteArrayOutputStream getContent() {
		return content;
	}

	/**
	 * setContent
	 * @param content
	 */
	public void setContent(ByteArrayOutputStream content) {
		this.content = content;
	}

 	/**
	 * setContent
	 * @param strContent
	 * @throws IOException
	 */
	public void setContent(String strContent) throws IOException {
		int outByte;
		StringReader reader = new StringReader(strContent);
		content = new ByteArrayOutputStream();
		while ((outByte = reader.read()) != -1) {
			content.write(outByte);
		}
		content.close();
	}
	
	/**
	 * Rappresentazione in stringa del
	 * contenuto dell'oggetto.
	 *
	 * @return contenuto come stringa.
	 */
	public String getContentToString() {
		String print = "";
		if (content != null) {
			print = content.toString();
		}
		return print;
	}

	/**
	 * Indica se il contenuto è vuoto
	 * @return isEmpty
	 */
	public boolean isEmpty() {
		return (content == null);
	}
	
	/**
	 * write
	 * @throws IOException
	 */
	public void write() throws IOException {
		write(getPath());
	}

	/**
	 * write
	 * @param filePath
	 * @throws IOException
	 */
	public void write(String filePath) throws IOException {
		write(new FileOutputStream(filePath));
	}

	/**
	 * write
	 * @param outputStream
	 * @throws IOException
	 */
	public void write(OutputStream outputStream) throws IOException {
		if (content != null && outputStream != null) {
			content.writeTo(outputStream);
			outputStream.close();
			content.close();
		}
	}

}
